package cn.lg.soar.boot.client.service.impl;

import cn.lg.soar.boot.client.entity.ClientUser;
import cn.lg.soar.boot.client.mapper.ClientUserMapper;
import cn.lg.soar.boot.client.service.ClientUserService;
import cn.lg.soar.boot.client.utils.JWTUtil;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.util.AssertUtil;
import cn.lg.soar.common.util.ParameterUtil;
import cn.lg.soar.database.base.service.impl.BaseServiceImpl;
import cn.lg.soar.database.query.SqueryWapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.security.SecureRandom;
import java.util.*;

/**
 * 用户信息表
 * @author ZhuanZ（无密码）
 * @since 2025-02-13
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Service
public class ClientUserServiceImpl extends BaseServiceImpl<ClientUserMapper, ClientUser> implements ClientUserService {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    private SqueryWapper<ClientUser> squeryWapperUser;

    // 通过token获取用户信息
    public ClientUser selectByToken(String accesstoken) {
        if (squeryWapperUser == null) {
            squeryWapperUser = new SqueryWapper<>(ClientUser.class);
        }
        QueryWrapper<ClientUser> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("token-eq~"+accesstoken);
        squeryWapperUser.setWhere(f, wrapper);
        return super.getOne(wrapper);
    }

    // 通过account获取用户信息
    public ClientUser selectByAccount(String account) {
        if (squeryWapperUser == null) {
            squeryWapperUser = new SqueryWapper<>(ClientUser.class);
        }
        QueryWrapper<ClientUser> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("account-eq~"+account);
        squeryWapperUser.setWhere(f, wrapper);
        return super.getOne(wrapper);
    }

    // 通过用户姓名获取用户信息
    public ClientUser selectByUserName(String userName) {
        if (squeryWapperUser == null) {
            squeryWapperUser = new SqueryWapper<>(ClientUser.class);
        }
        QueryWrapper<ClientUser> wrapper = Wrappers.query();
        List<String> f = new ArrayList<>();
        f.add("userName-eq~"+userName);
        squeryWapperUser.setWhere(f, wrapper);
        return super.getOne(wrapper);
    }

    /**
     * 初始化用户
     *
     * @param data
     */
    @Transactional
    public ClientUser initUser(ClientUser data) {
        String salt = randomSalt();
        SimpleHash hash = new SimpleHash("md5", "123456", salt, 2);
        data.setSalt(salt);                                          // 密码盐
        data.setPassword(hash.toHex());                              // 登录密码
        String token = JWTUtil.sign(data);
        data.setToken(token);                             // 访问令牌
        return data;
    }

    /**
     * 生成随机盐
     */
    private static String randomSalt()
    {
        // 定义盐字符集
        String saltChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random random = new SecureRandom();
        for (int i = 0; i < 16; i++) {
            salt.append(saltChars.charAt(random.nextInt(saltChars.length())));
        }
        return salt.toString();
    }
}
